package com.example.Controller;

import com.example.Service.impl.InteractionServiceImpl;
import com.example.Service.impl.TaskServiceImpl;
import com.example.util.Result;
import com.example.pojo.Interaction;
import com.example.pojo.Task;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

@RestController
@RequestMapping("/interaction")
@Api(tags = "通信管理")
public class InteractionController {

    @Autowired
    private InteractionServiceImpl interactionService;

    @Autowired
    private TaskServiceImpl taskService;

    //所有联系人的展示 只能展示同部门还有权限比自己底的
    @GetMapping("/selectAll")
    public Result selectAllPeople() {
        List<Interaction> interactionList = interactionService.selectAllPeople();
        return new Result("200","查询成功",interactionList);
    }


    //登录人点击联系人 展示登录人（主人公）和联系人 通信内容
    @GetMapping("/messages/conversations")
    public Result selectMessagesUserConversations(@RequestParam(required = false, defaultValue = "null") String sender,
                                                  @RequestParam(required = false, defaultValue = "null") String recipient) {
        List<Interaction> interactionList = interactionService.selectMessagesUserConversations(sender, recipient);
        return new Result("200", "查询成功", interactionList);
    }



    //通知 -> 任务通知 -> 发送信息 正常交流的函数 (发送给谁?)
    @PostMapping("/sendMessageByNameAndRecipient")
    public Result sendMessageByName(@RequestBody Interaction interaction){
        System.out.println(interaction);
        interactionService.insertSendMessageByNameAndRecipient(interaction);
        return new Result("200","发布成功");
    }
//    @PostMapping("/sendMessageByNameAndRecipient")
//    public ResponseEntity<String> sendMessageByNameAndRecipient(@RequestParam("file") MultipartFile file) {
//        try {
//            // 处理文件上传逻辑
//            byte[] fileBytes = file.getBytes();
//            // 将 fileBytes 保存到数据库或其他存储位置
//            return ResponseEntity.ok("文件上传成功");
//        } catch (Exception e) {
//            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
//        }
//    }

    //所有任务可以导出 功能
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<Task> taskList = taskService.selectAll();

        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("type", "任务类型");


        writer.addHeaderAlias("level", "难易程度");
        writer.addHeaderAlias("formType", "发送级别");

        writer.addHeaderAlias("name", "创作者");
        writer.addHeaderAlias("taskname", "任务名称");

        writer.addHeaderAlias("context", "任务内容");
        writer.addHeaderAlias("startTime", "开始时间");

        writer.addHeaderAlias("stopTime", "结束时间");
        writer.addHeaderAlias("description", "描述");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (Task task : taskList) {
            if (task.getStartTime() != null) {
                try {
                    // 如果task.getStopTime()已经是一个LocalDateTime对象，则不需要解析，直接使用即可
                    task.setStopTime(task.getStartTime());
                } catch (DateTimeParseException e) {
                    // 日期格式不正确，记录日志或处理异常
                    System.out.println("日期格式不正确: " + task.getStartTime());
                }
            }
            if (task.getStopTime() != null) {
                try {
                    // 如果task.getStopTime()已经是一个LocalDateTime对象，则不需要解析，直接使用即可
                    task.setStopTime(task.getStopTime());
                } catch (DateTimeParseException e) {
                    // 日期格式不正确，记录日志或处理异常
                    System.out.println("日期格式不正确: " + task.getStopTime());
                }
            }
            if (task.getUpdateTime() != null) {
                try {
                    // 如果task.getStopTime()已经是一个LocalDateTime对象，则不需要解析，直接使用即可
                    task.setStopTime(task.getUpdateTime());
                } catch (DateTimeParseException e) {
                    // 日期格式不正确，记录日志或处理异常
                    System.out.println("日期格式不正确: " + task.getUpdateTime());
                }
            }
        }
        writer.setOnlyAlias(true);
        writer.write(taskList, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("任务信息", "UTF-8" );

        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream os = response.getOutputStream();

        writer.flush(os);
        writer.close();
    }


}
